#include "convertdialog.h"
#include "ui_convertdialog.h"
#include<QDebug>
#include<QTextCodec>
#include<QFile>
#include<QMessageBox>
#include<QFileDialog>


ConvertDialog::ConvertDialog(QString filepath,QString coding,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConvertDialog)
  ,filepath(filepath)
  ,coding(coding)
{
    ui->setupUi(this);

    ui->srcSelector->setCurrentText(coding);
    destCoding = ui->destSelector->currentText();

    if(!filepath.isEmpty()){

        QString prefixPath = filepath.left(filepath.lastIndexOf("/"));
        filename = filepath.mid(filepath.lastIndexOf("/")+1);

        ui->src->setText(filename);

        destFilename = "copying-"+filename;

        ui->dest->setText(destFilename);
        destFilepath = prefixPath+"/"+destFilename;




    }
}

ConvertDialog::~ConvertDialog()
{
    delete ui;
}

void ConvertDialog::on_pushButton_clicked()
{

    int r = QMessageBox::question(this,"文件转码","确定要转码吗？",QMessageBox::Ok,QMessageBox::Cancel);

    if(r == QMessageBox::Ok){
//        QTextCodec *srcCodec = QTextCodec::codecForName();

        QFile f1(filepath);
        QFile f2(destFilepath);




        if (f1.open(QIODevice::ReadOnly | QIODevice::Text)
                &&f2.open(QIODevice::WriteOnly|QIODevice::Text)
                ) {
                QTextStream in(&f1);

                in.setCodec(coding.toLatin1().data());

                QTextStream out(&f2);

                out.setCodec(destCoding.toLatin1().data());

                out<<in.readAll();



         }
         f1.close();
    }




    qDebug() << "convert coding over";
}


void ConvertDialog::on_srcSelector_currentIndexChanged(const QString &arg1)
{
    coding = arg1;
}

void ConvertDialog::on_destSelector_currentIndexChanged(const QString &arg1)
{
    destCoding = arg1;
}

void ConvertDialog::on_pushButton_2_clicked()
{
    filepath = QFileDialog::getOpenFileName();
    filename = filepath.mid(filepath.lastIndexOf("/")+1);
    ui->src->setText(filename);
}

void ConvertDialog::on_pushButton_3_clicked()
{
    destFilepath = QFileDialog::getSaveFileName();
    destFilename = destFilepath.mid(filepath.lastIndexOf("/")+1);
    ui->dest->setText(destFilename);
}
